import Echart from './components/echart.js';
import {Button,Row,Col,Card,Form,DatePicker,Space,} from 'antd';
import React, { useState, useEffect } from 'react';
import moment from 'moment';
import { ProFormSelect } from '@ant-design/pro-form';
import {querySysmemberList,queryStatstics,queryCarDetail} from './service';

const TableList = () => {
  const [queryForm] = Form.useForm();
  const [cardList, setCardList] = useState({});
  const [driverList, setDriverList] = useState({});
  const [testerList, setTesterList] = useState({});
  const [taskCount, setTaskCount] = useState(0);
  const [timeCount, setTimeCount] = useState(0);
  const [eventListData, setEventListData] = useState([]);
  const { RangePicker } = DatePicker;
  const [formQueryList, setFormQueryList] = useState({
    limit: 100000, //
    group: '', // 部门名称
    user_type: 0, // 类型，1：司机  2：测试人员
    car_id: '', // 车牌号
    offset: 0, //
    start_day: moment().year() + '-01-01',
    end_day: moment().year() + '-12-31',
  });
  const [timesDetails, setTimesDetails] = useState([]);
  const [lastTimeDetails, setLastTimeDetails] = useState([]);

  const defs = [{
    dataKey: 'mon',
  }, {
    dataKey: 'cnt',
    tickCount: 5,
  }];

  const resetFormList = () => {
    queryForm.resetFields();
    handleQueryPageList({
      limit: 100000, //
      group: '', // 部门名称
      user_type: 0, // 类型，1：司机  2：测试人员
      car_id: '', // 车牌号
      offset: 0, //
      start_day: moment().year() + '-01-01',
      end_day: moment().year() + '-12-31',
    });
    setFormQueryList({
      limit: 100000, //
      group: '', // 部门名称
      user_type: 0, // 类型，1：司机  2：测试人员
      car_id: '', // 车牌号
      offset: 0, //
      start_day: moment().year() + '-01-01',
      end_day: moment().year() + '-12-31',
    });
  };

  const handleQueryPageList = async (payloads) => {
    setEventListData([]);
    const paramPlain = payloads || formQueryList;
    const data = {
      ...paramPlain,
      driver_id: parseInt(paramPlain.driver_id),
      testor_id: parseInt(paramPlain.testor_id)
    };
    await queryStatstics(data)
      .then(({code, data, msg}) => {
        if (code === '200') {
          setTaskCount(data.totalCarAppointmentTimes);
          setTimeCount(data.totalCarAppointmentLastTime);
          setTimesDetails(data.timesDetails);
          setLastTimeDetails(data.lastTimeDetails);
        }
      })
      .catch(() => {})
  };

  useEffect(() => {
    queryCarDetail({limit: 100000, offset: 0}).then(({code, data=[],msg}) => {
      if (code === '200') {
        const normalData = (data ?? []).reduce((next, {card, car_id}) => ({...next, [car_id]: card}), {})
        console.log('renqing: ' + JSON.stringify(normalData))
        setCardList(normalData);
      } else {
        setCardList({});
      }
    }).catch(() => {});
    querySysmemberList({limit: 100000, offset: 0, type: 1}).then(({code, data=[],msg}) => {
      if (code === '200') {
        const normalData = (data ?? []).reduce((next, {name, id}) => ({...next, [id]: name}), {})
        setDriverList(normalData);
      } else {
        setDriverList({});
      }
    }).catch(() => {});
    querySysmemberList({limit: 100000, offset: 0, type: 2}).then(({code, data=[],msg}) => {
      if (code === '200') {
        const normalData = (data ?? []).reduce((next, {name, id}) => ({...next, [id]: name}), {})
        setTesterList(normalData);
      } else {
        setTesterList({});
      }
    }).catch(() => {});
    handleQueryPageList();
  }, []);

  function onChange(dates, dateStrings) {
    console.log('From: ', dates[0], ', to: ', dates[1]);
    console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
    let data = formQueryList;
    data.start_day = dateStrings[0];
    data.end_day = dateStrings[1];
    setFormQueryList(data);
  }

  return (
    <>
      <div
        style={{ marginBottom: '16px', padding: '24px', paddingBottom: '0', background: '#fff' }}
      >
        <Form
          form={queryForm}
          layout="horizontal"
          labelCol={{ md: 8, sm: 24, xs: 24 }}
          wrapperCol={{ md: 16, sm: 24, xs: 24 }}
          onValuesChange={(changeValues) => setFormQueryList({ ...formQueryList, ...changeValues })}
        >
          <Row gutter={24}>
            <Col md={8} sm={24} xs={24}>
              <ProFormSelect name="car_id" label="车牌号码" showSearch valueEnum={cardList} />
            </Col>
            <Col md={8} sm={24} xs={24}>
              <ProFormSelect name="driver_id" label="司机" showSearch valueEnum={driverList} />
            </Col>
            <Col md={8} sm={24} xs={24}>
              <ProFormSelect name="testor_id" label="测试人员" showSearch valueEnum={testerList} />
            </Col>
            <Col md={8} sm={24} xs={24}>
              <Form.Item name="time" label="时间段">
                <RangePicker
                  ranges={{
                    '今天': [moment(), moment()],
                    '这个月': [moment().startOf('month'), moment().endOf('month')],
                  }}
                  onChange={onChange}
                />
              </Form.Item>
            </Col>
            <Col md={16} sm={24} xs={24}>
              <Form.Item label="&nbsp;" colon={false}>
                <Row justify="end">
                  <Space>
                    <Button onClick={() => handleQueryPageList()}>搜索</Button>
                    <Button onClick={() => resetFormList()}>重置</Button>
                  </Space>
                </Row>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
      <Card style={{ marginTop: 8}} gutter={8} title={`任务总次数：${taskCount?taskCount:0}次 \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  任务总累计时长：${timeCount?timeCount:0}小时`}>
        <Row gutter={24}>
          <Col md={11} sm={24} xs={24} >
            <Echart data={timesDetails} defs={defs} />
          </Col>
          <Col md={11} sm={24} xs={24} offset={1}>
            <Echart data={lastTimeDetails} defs={defs}/>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col md={6} sm={24} xs={24} offset={6}>
            任务次数
          </Col>
          <Col md={6} sm={24} xs={24} offset={5}>
            任务累计时长（小时）
          </Col>
        </Row>
      </Card>
    </>
  );
}

export default TableList;